<?php

namespace App\Http\Controllers\Skill;

use App\Http\Controllers\Controller;
use App\Models\Skill;
use Illuminate\Http\Request;
use App\Http\Requests\Skill\SkillRequest;
use Auth;

class SkillController extends Controller
{
    /**
     * 创建技能
     * @param SkillRequest $request
     * @return mixed
     */
    public function create(SkillRequest $request)
    {
        $user = Auth::guard('api')->user();
        $type = $request->get('type', 'create');
        $request->merge(['user_id' => $user->id]);
        $request['skill_intro'] = json_encode($request['skill_intro']);

        if($type === 'create') {
            Skill::create($request->all());
            return $this->success('创建成功', null);
        } else if($type === 'update') {
            $id = $request->get('id');
            if($skill = Skill::where('id', $id)->first()) {
                $skill->update($request->all());
                return $this->success('更新成功', null);
            }
            return $this->error('未找到数据', null);
        }

        return $this->unValidate('未找到类型');


    }

    /**
     * 获取列表
     * @return mixed
     */
    public function list(Request $request)
    {
        $user = Auth::guard('api')->user();
        $data = array();

        $hidden = $request->get('type', 'hidden');
        $hidden === 'hidden' && ($data['hidden'] = 0);
        $hidden === 'show' && ($data['hidden'] = 1);

        $list = Skill::where('user_id', $user ? $user->id : 1)->where($data)->get();
        return $this->success('创建成功', $list);
    }

    /**
     * 切换是否启用
     * @param Skill $skill
     * @return mixed
     */
    function switch(Skill $skill)
    {
        $skill->hidden = $skill->hidden ? 0 : 1;
        $skill->save();
        return $this->success('修改成功', null);
    }
}
